/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-05-24 22:41:23
 * @LastEditTime: 2022-05-25 23:45:01
 * @LastEditors: Junhuang
 * @Reference:
 */
'use strict';

const Controller = require('egg').Controller;

// 参数校验规则
const rules = {
  type: { type: 'int', required: true, desc: '推荐位类别' },
  cover: { type: 'string', required: true, desc: '推荐位照片' },
  status: { type: 'int', required: true, desc: '推荐位状态' },
  video_id: { type: 'int', required: true, desc: '推荐作品id' },
};

class AdvertisementController extends Controller {

  // 获取推荐列表-前台，不需要权限
  // 示例：http://127.0.0.1:7001/advertisement_list/1?limit=10&type=1
  async index() {
    const { ctx, app } = this;
    const type = ctx.query.type;
    const where = {};
    where.status = 1;
    if (type) {
      where.type = type * 1;
    }
    // 参数验证
    ctx.validate({
      page: {
        required: true,
        type: 'int',
        desc: '第几页',
      },
      limit: {
        required: false,
        type: 'int',
        desc: '每页几条',
      },
    });

    const res = await ctx.page(ctx.model.Advertisement, where,
      {
        include: [{
          model: app.model.Video,
          required: false,
          attributes: [ 'id', 'title', 'cover', 'status', 'play_count', 'danmu_count', 'created_time' ],
          include: [{
            model: app.model.Category,
            attributes: [ 'id', 'title' ],
          }],
        }],
        order: [[ 'type', 'ASC' ], [ 'id', 'ASC' ]],
      });
    return ctx.apiSuccesss(res);
  }

  // 后台列表分页
  async list() {
    const { ctx, app } = this;
    const where = {};
    const video_where = {}; // 作品查询条件
    const Op = app.Sequelize.Op;

    // 组织查询条件
    // 评论id用全等
    if (ctx.query.id && ctx.query.id.length > 0) {
      where.id = ctx.query.id;
    }

    // 推荐类别
    if (ctx.query.type && ctx.query.type.length > 0) {
      where.type = ctx.query.type;
    }

    // stauts全等
    if (ctx.query.status) {
      where.status = parseInt(ctx.query.status);
    }

    // 作品标题用like
    if (ctx.query.title && ctx.query.title.length > 0) {
      video_where.title = {
        [Op.like]: '%' + ctx.query.title + '%',
      };
    }

    // const sequelize = app.model;
    const options = {
      include: [{
        model: app.model.Video,
        attributes: [ 'id', 'title', 'cover', 'status' ],
        include: [{
          model: app.model.User,
          attributes: [ 'id', 'username', 'nickname', 'avatar' ],
        }],
        where: video_where,
      }],
      order: [[ 'type', 'ASC' ], [ 'id', 'ASC' ]],
    };

    const res = await ctx.pageAndCount(app.model.Advertisement, where, options);
    const items = [];
    res.rows.forEach(el => {
      const item = JSON.parse(JSON.stringify(el));
      if (el.video) {
        item.video_title = el.video.title;
        item.video_cover = el.video.cover;
        item.video_status = el.video.status;
        if (el.video.user) {
          item.user_nickname = el.video.user.nickname;
          item.user_username = el.video.user.username;
          item.user_id = el.video.user.id;
          item.user_avatar = el.video.user.avatar;
        }
        delete item.video;
      }
      items.push(item);
    });
    ctx.apiSuccesss({
      total: res.count,
      items,
    });
  }

  // 更改推荐位状态
  // '/advertisement/:id/status'
  async changeStatus() {
    const { ctx, app } = this;
    let { status } = ctx.request.body;
    status = parseInt(status);
    ctx.validate({
      id: {
        required: true,
        type: 'int',
        desc: 'id',
      },
      status: {
        required: true,
        type: 'int',
        desc: 'status',
      },
    });

    const advertisement = await app.model.Advertisement.findOne({
      where: {
        id: ctx.params.id,
      },
    });

    if (!advertisement) {
      return ctx.throw(404, '该推荐位不存在');
    }

    if (advertisement.status === status) {
      return ctx.throw('该推荐位状态与要变化的状态一致，不用变化！');
    }

    advertisement.status = status;
    advertisement.save();

    const res = JSON.parse(JSON.stringify(advertisement));
    return ctx.apiSuccesss(res);
  }

  // 新增推荐位
  async save() {
    const { ctx, app } = this;
    const {
      type,
      cover,
      status,
      video_id,
      description,
    } = ctx.request.body;

    ctx.validate({
      ...rules,
    });


    const ad = await app.model.Advertisement.create({
      type,
      cover,
      status,
      video_id,
      description,
    });

    const res = await app.model.Advertisement.findOne({
      where: {
        id: ad.id,
      },
      include: [{
        model: app.model.Video,
        attributes: [ 'id', 'title', 'cover', 'status' ],
        include: [{
          model: app.model.User,
          attributes: [ 'id', 'username', 'nickname', 'avatar' ],
        }],
      }],
    });

    const item = JSON.parse(JSON.stringify(res));
    if (item.video) {
      item.video_title = item.video.title;
      item.video_cover = item.video.cover;
      item.video_status = item.video.status;
      if (item.video.user) {
        item.user_nickname = item.video.user.nickname;
        item.user_username = item.video.user.username;
        item.user_id = item.video.user.id;
        item.user_avatar = item.video.user.avatar;
      }
      delete item.video;
    }
    return ctx.apiSuccesss(item);
  }

  // 修改推荐位
  async update() {
    const { ctx, app } = this;
    const {
      type,
      cover,
      status,
      video_id,
      description,
    } = ctx.request.body;

    ctx.validate({
      id: {
        required: true,
        type: 'int',
        desc: '角色id',
      },
      ...rules,
    });


    const ad = await app.model.Advertisement.findOne({
      where: {
        id: ctx.params.id,
      },
    });

    if (!ad) {
      return ctx.throw(404, '该推荐位不存在');
    }

    await ad.update({
      type,
      cover,
      status,
      video_id,
      description,
    });

    const res = await app.model.Advertisement.findOne({
      where: {
        id: ctx.params.id,
      },
      include: [{
        model: app.model.Video,
        attributes: [ 'id', 'title', 'cover', 'status' ],
        include: [{
          model: app.model.User,
          attributes: [ 'id', 'username', 'nickname', 'avatar' ],
        }],
      }],
    });

    const item = JSON.parse(JSON.stringify(res));
    if (item.video) {
      item.video_title = item.video.title;
      item.video_cover = item.video.cover;
      item.video_status = item.video.status;
      if (item.video.user) {
        item.user_nickname = item.video.user.nickname;
        item.user_username = item.video.user.username;
        item.user_id = item.video.user.id;
        item.user_avatar = item.video.user.avatar;
      }
      delete item.video;
    }
    return ctx.apiSuccesss(item);
  }
}

module.exports = AdvertisementController;
